<template>
  <ion-page>
    <ion-header>
      <ion-toolbar>
        <ion-buttons slot="start">
          <ion-button @click="goBack"><ion-icon :icon="chevronBackOutline"></ion-icon></ion-button>
        </ion-buttons>
        <ion-title text-align="center">LogsList</ion-title>
        <ion-buttons slot="end">
          <ion-button @click="openCreateModal"><ion-icon :icon="addOutline"></ion-icon></ion-button>
        </ion-buttons>
      </ion-toolbar>
    </ion-header>

    <ion-content>
      <!-- 有数据时显示日志列表 -->
      <template v-if="logs.length">
        <ion-card v-for="log in logs" :key="log.commentId" style="background-color: bisque;">
          <ion-grid>
            <ion-list>
              <ion-item>
                <ion-row 
                  @touchstart="startLongPress($event, log.commentId)"
                  @touchend="cancelLongPress"
                  @mousedown="startLongPress($event, log.commentId)"
                  @mouseup="cancelLongPress"
                  @mouseleave="cancelLongPress"
                  class="log-row"
                >
                  <ion-col size="1.5">BA:</ion-col>             
                  <ion-col size="3.5" @click="toggleExpand(log.commentId)">{{ log.name }}</ion-col>
                  <ion-col size="7" @click="toggleExpand(log.commentId)" style="color: #666;font-size: 0.9em">{{ log.date }}</ion-col>
                  <ion-col size="12" @click="toggleExpand(log.commentId)">
                    <div class="comment-preview">{{ log.comment }}</div>
                  </ion-col>
                </ion-row>
              </ion-item> 
              <!-- 展开详情 -->
              <div v-show="expandedLogId === log.commentId" class="detail-panel">
                <div class="detail-content">
                  <h5 style="color: black;">content: </h5>
                  <h4>{{ log.comment }}</h4>
                </div>
              </div>
            </ion-list>
          </ion-grid>
        </ion-card>
      </template>
      
      <!-- 没有数据时显示空状态 -->
      <div v-else class="empty-state-container">
        <div class="empty-state">
          <ion-icon :icon="documentTextOutline" size="large"></ion-icon>
          <p>No data available</p>
          <ion-button fill="outline" @click="openCreateModal">Create New Log</ion-button>
        </div>
      </div>
      
      <!-- 新建日志模态框 -->
      <ion-modal :is-open="isCreateModalOpen">
        <ion-header>
          <ion-toolbar>
            <ion-title>new logs</ion-title>
            <ion-buttons slot="end">
              <ion-button @click="closeCreateModal">close</ion-button>
            </ion-buttons>
          </ion-toolbar>
        </ion-header>
        <ion-content class="ion-padding">
          <ion-textarea 
            v-model="newLog.content" 
            placeholder="please enter..." 
            fill="outline"
            :auto-grow="true"
            :rows="2"
            :maxlength="500"
            class="log-textarea"
          ></ion-textarea>
          <ion-button expand="block" @click="createLog" class="submit-btn">post</ion-button>
        </ion-content>
      </ion-modal>
    </ion-content>
  </ion-page>
</template>

<script setup lang="ts">
import { 
  IonPage, IonHeader, IonToolbar, IonTitle, IonContent, 
  IonGrid, IonCol, IonList, IonRow, IonButton,
  IonModal, IonButtons, IonItem, IonIcon, IonCard, IonTextarea
} from '@ionic/vue';
import { chevronBackOutline, addOutline, documentTextOutline } from 'ionicons/icons';
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { watch } from 'vue';
import { useRoute } from 'vue-router';
import logapi from '@/api/logapi'

const route = useRoute();

watch(() => route.path, (newPath) => {
  if (!newPath.includes('/logs')) { 
    (document.activeElement as HTMLElement)?.blur();
  }
});

const goBack = () => {
  router.go(-1); 
};

interface Log {
  commentId: string;
  comment: string;
  name: string;
  date: string;
  comments?: Comment[];
}

interface Comment {
  commentId: string;
  comment: string;
  date: string;
  name: string;
}

const router = useRouter();
const logs = ref<Log[]>([]);
const isCreateModalOpen = ref(false);
const newLog = ref({
  content: ''
});
const expandedLogId = ref<string | null>(null);
const accessToken = localStorage.getItem('accessToken');
const longPressTimer = ref<number | null>(null);
const longPressCommentId = ref<string | null>(null);
const touchStartX = ref(0);
const touchStartY = ref(0);

// 切换展开状态
const toggleExpand = (logId: string) => {
  expandedLogId.value = expandedLogId.value === logId ? null : logId;
};

const startLongPress = (event: TouchEvent | MouseEvent, commentId: string) => {
  if (event instanceof TouchEvent) {
    touchStartX.value = event.touches[0].clientX;
    touchStartY.value = event.touches[0].clientY;
  }
  
  longPressCommentId.value = commentId;
  longPressTimer.value = window.setTimeout(() => {
    deleteLog(commentId);
  }, 1000);
};

const cancelLongPress = (event?: TouchEvent | MouseEvent) => {
  if (longPressTimer.value) {
    // 如果是触摸事件且移动距离超过阈值，则不触发展开
    if (event instanceof TouchEvent && event.changedTouches.length > 0) {
      const deltaX = Math.abs(event.changedTouches[0].clientX - touchStartX.value);
      const deltaY = Math.abs(event.changedTouches[0].clientY - touchStartY.value);
      
      if (deltaX > 10 || deltaY > 10) {
        clearTimeout(longPressTimer.value);
        longPressTimer.value = null;
        longPressCommentId.value = null;
        return;
      }
    }
    
    clearTimeout(longPressTimer.value);
    longPressTimer.value = null;
    if (longPressCommentId.value) {
      toggleExpand(longPressCommentId.value);
      longPressCommentId.value = null;
    }
  }
};

// 获取日志列表
const fetchLogs = async () => {
  try {
    const { data } = await logapi.get('/shift/handover/log/list', {
      params: {
        start: 0,
        length: 200
      }
    });
    logs.value = data.data.list || [];
  } catch (error) {
    console.error('获取日志失败:', error);
    logs.value = [];
  }
};

// 删除日志
const deleteLog = async (commentId: string) => {
  const confirm = window.confirm('User can only delete his/her message! Confirm this action?');
  if (!confirm) return;
  try {
    await logapi.post(`/shift/handover/log/delete`,
      {  
        commentId,
        userId: localStorage.getItem('userId'),
      }
    );
    await fetchLogs();
  } catch (error) {
    console.error('删除失败:', error);
  }
};

// 新建日志
const createLog = async () => {
  if (!newLog.value.content.trim()) {
    alert('Please enter log content');
    return;
  }
  
  try {
    const requestData = {
      comment: newLog.value.content,
      userId: localStorage.getItem('userId')
    };
    await logapi.post('/shift/handover/log/add', requestData, {
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${accessToken}` 
      },
    });
    closeCreateModal();
    await fetchLogs();
    newLog.value.content = '';
  } catch (error: any) {
    if (error.response) {
      if (error.response.status === 403) {
        alert('权限不足，请联系管理员');
      } else if (error.response.status === 500) {
        alert('服务器错误：' + error.response.data.msg);
      }
    }
    
    if (error.response?.status === 401) {
      router.push('/login');
    }
  }
};

// 模态框控制
const openCreateModal = () => isCreateModalOpen.value = true;
const closeCreateModal = () => {
  isCreateModalOpen.value = false;
  newLog.value.content = '';
};

onMounted(fetchLogs);
</script>

<style scoped>
.log-row {
  display: flex;
  align-items: center;
  width: 100%;
}

.comment-preview {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
  display: block;
  padding: 8px 0;
  line-height: 1.4;
}

.empty-state-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 70vh;
}

.empty-state {
  text-align: center;
  padding: 2rem;
  color: #6c757d;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1rem;
}

.empty-state p {
  margin: 0.5rem 0;
  font-size: 1.2rem;
  color: #495057;
}

.submit-btn {
  margin-top: 20px;
}

ion-modal {
  --width: 80%;
  --height: 50%;
  --border-radius: 16px;
}

ion-toolbar ion-title {
  padding: 0 20px;
}

.detail-panel {
  width: 100%;
  padding: 12px;
  background: #f8f9fa;
  border-top: 1px solid #eee;
  animation: slideDown 0.3s ease;
}

.detail-content {
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.log-textarea {
  --background: #f8f9fa;
  --padding-start: 12px;
  --padding-end: 12px;
  --padding-top: 12px;
  --padding-bottom: 12px;
  border-radius: 8px;
  transition: height 0.2s ease;
  min-height: 100px;
  max-height: 300px;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 优化点击区域 */
ion-col {
  user-select: none;
  -webkit-user-select: none;
}

/* 防止快速点击多次触发 */
ion-col[size="1.5"],
ion-col[size="3.5"],
ion-col[size="7"],
ion-col[size="12"] {
  pointer-events: auto;
}

/* 长按提示效果 */
.log-row:active {
  background-color: rgba(0, 0, 0, 0.05);
  transition: background-color 0.1s;
}
</style>